package com.cheesmo.nzb.client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.net.SocketException;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

import org.apache.commons.net.nntp.NNTPClient;

public class NNTPConnection
{
	boolean inUse = false;
	NNTPClient client = new NNTPClient();
	ClientConfig config;

	protected void setInUse(boolean value)
	{
		this.inUse = value;
	}

	public boolean isInUse() {
		return this.inUse;
	}

	public NNTPConnection(ClientConfig config) {
		this.config = config;
	}

	private void tryConnect()
			throws SocketException, IOException
	{
		if (!this.client.isConnected())
			try {
				connect();
			} catch (Exception e) {
				try {
					Thread.sleep(500L);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				connect();
			}
	}

	private void connect() throws SocketException, IOException {
		this.client.connect(this.config.getServer(), this.config.getPort());
		if (this.config.requiresAuthentication()) {
			this.client.authenticate(this.config.getUsername(), this.config.getPassword());
		}

		System.err.println("connected: " + this.client.isConnected());
	}

	public void tryDisconnect()
	{
		if (this.client != null)
			try {
				this.client.disconnect();
			} catch (Throwable localThrowable)
			{
			}
	}

	public boolean downloadSegment(String group, String string, String downloadName) {
		try {
			tryConnect();
			this.client.selectNewsgroup(group);
			Reader reader = this.client.retrieveArticleBody(string);

			if (reader != null) {
				FileOutputStream fos = new FileOutputStream(this.config.getCacheDir() + File.separator + downloadName);
				char[] buffer = new char[512];
				int charsRead = reader.read(buffer);
				while ((charsRead > -1) && (this.client.isConnected())) {
					fos.write(Charset.forName("ISO-8859-1").encode(CharBuffer.wrap(buffer, 0, charsRead)).array());
					charsRead = reader.read(buffer);
				}

				if (!this.client.isConnected()) {
					System.out.println("Client disconnected.");
				}
				reader.close();
				fos.flush();
				fos.close();
				return true;
			}

		} catch (SocketException e)
		{
			System.out.println("Client disconnected. " + e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
